package com.example.demo.Controller;

import com.example.demo.Service.AdministratorService;
import com.example.demo.repository.domain.Administrator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ZhangKe
 * @Description
 * @date 2019/7/3 13:19.
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/admin")
public class AdministratorController {

    @Autowired
    private AdministratorService administratorService;


    @ResponseBody
    @GetMapping("/info/{id}")
    public Administrator getById(@PathVariable(value = "id") int id, HttpServletRequest request){
        Administrator customer=administratorService.getById(id);
        request.getSession().setAttribute("admin",customer);
        return customer;
    }

    @ResponseBody
    @GetMapping("/info")
    public Administrator test(HttpServletRequest request){
        return (Administrator)request.getSession().getAttribute("admin");
    }

    @PostMapping("/register")
    public int register(@RequestParam(value = "adminName")String adminName,
                        @RequestParam(value = "adminPassword")String adminPassword){
        Administrator admin=new Administrator();
        admin.setAdministratorName(adminName);
        admin.setAdministratorPassword(adminPassword);
        int result=administratorService.register(admin);
        if (result>0){
            return admin.getAdministratorNo();
        }else{
            return 0;
        }
    }

    /**
     *
     * @param adminName
     * @param adminPassword
     * @param request
     * @return  登陆成功，用户信息存入session；返回用户信息
     *           登陆失败，用户不存在，或密码错误
     */
    @PostMapping("/login")
    public Administrator login(@RequestParam(value = "adminName")String adminName,
                     @RequestParam(value = "adminPassword")String adminPassword,
                     HttpServletRequest request){
        int result=administratorService.login(adminName,adminPassword);
        if (result==1){
            Administrator admin=administratorService.getByName(adminName);
            request.getSession().setAttribute("admin",admin);
            return admin;
        }else
            return null;
    }

}
